package org.study.stream;

import java.util.stream.LongStream;
import java.util.stream.Stream;

/**
 * 参考 https://www.it1352.com/1729542.html
 *
 * @author Administrator
 * @date 2022-12-27
 */
public class StreamTest05 {
    public static void main(String[] args) {
        System.out.println(parallelSum01(100_000_000));
        System.out.println(parallelSum02(100_000_000));
    }

    private static Long parallelSum01(long n) {
        long start = System.currentTimeMillis();
        Long reduce = Stream.iterate(1L, i -> i + 1)
                .limit(n)
                .parallel()
                .reduce(0L, Long::sum);
        System.out.println("使用 parallel、reduce 耗时：" + (System.currentTimeMillis() - start));
        return reduce;
    }

    public static long parallelSum02(long n) {
        long start = System.currentTimeMillis();
        long sum = LongStream.rangeClosed(1, n).parallel().sum();
        System.out.println("使用 parallel、sum 耗时：" + (System.currentTimeMillis() - start));
        return sum;
    }
}
